import os
import re
import argparse
from datetime import datetime
import time
import signal


parser = argparse.ArgumentParser()
parser.add_argument('IpAddr', type=str, help='Ping this Ip Addrsss')
args = parser.parse_args()


def exit_program(signum, frame):
    print('Program is stopped by user.')
    exit()


signal.signal(signal.SIGINT, exit_program)
signal.signal(signal.SIGTERM, exit_program)


def ping_address(address):
    command_str = 'ping -n 1 %s' % args.IpAddr
    result_string = os.popen(command_str).read()
    result = result_string.split('\n')[2].split()
    if len(result) < 6:
        interval = 4000
    else:
        interval = result[-2].split('=')[1]
        interval = int(re.sub('\D', '', interval))
    return interval


def main():
    while True:
        interval = ping_address(args.IpAddr)
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(current_time, 'Ping', args.IpAddr, 'RTT=%dms' % interval)
        time.sleep(2)


if __name__ == '__main__':
    main()
